#include "quihelper.h"
#include "qnetworkinterface.h"
#include "qnetworkproxy.h"

#define TIMEMS qPrintable(QTime::currentTime().toString("HH:mm:ss zzz"))

int QUIHelper::getScreenIndex()
{
    //需要对多个屏幕进行处理
    int screenIndex = 0;
#if (QT_VERSION >= QT_VERSION_CHECK(5,0,0))
    int screenCount = qApp->screens().size();
#else
    int screenCount = qApp->desktop()->screenCount();
#endif

    if (screenCount > 1) {
        //找到当前鼠标所在屏幕
        QPoint pos = QCursor::pos();
        for (int i = 0; i < screenCount; ++i) {
#if (QT_VERSION >= QT_VERSION_CHECK(5,0,0))
            if (qApp->screens().at(i)->geometry().contains(pos)) {
#else
            if (qApp->desktop()->screenGeometry(i).contains(pos)) {
#endif
                screenIndex = i;
                break;
            }
        }
    }
    return screenIndex;
}


QRect QUIHelper::getScreenRect(bool available)
{
    QRect rect;
    int screenIndex = QUIHelper::getScreenIndex();
    if (available) {
#if (QT_VERSION >= QT_VERSION_CHECK(5,0,0))
        rect = qApp->screens().at(screenIndex)->availableGeometry();
#else
        rect = qApp->desktop()->availableGeometry(screenIndex);
#endif
    } else {
#if (QT_VERSION >= QT_VERSION_CHECK(5,0,0))
        rect = qApp->screens().at(screenIndex)->geometry();
#else
        rect = qApp->desktop()->screenGeometry(screenIndex);
#endif
    }
    return rect;
}

qreal QUIHelper::getScreenRation(bool devicePixel)
{
    qreal ratio=1.0;
    int screenIndex=getScreenIndex();
    QScreen *screen=qApp->screens().at(screenIndex);
    if(devicePixel)
    {
        //需要开启AA_EnableHighDpiScaling 属性才能正常获取
        ratio=screen->devicePixelRatio()*100;
    }
    else
    {
        ratio=screen->logicalDotsPerInch();
    }

    return ratio/96;
}

QRect QUIHelper::checkCenterRect(QRect &rect, bool available)
{
    QRect deskRect = QUIHelper::getScreenRect(available);
    int formWidth = rect.width();
    int formHeight = rect.height();
    int deskWidth = deskRect.width();
    int deskHeight = deskRect.height();
    int formX = deskWidth / 2 - formWidth / 2 + deskRect.x();
    int formY = deskHeight / 2 - formHeight / 2;
    rect = QRect(formX, formY, formWidth, formHeight);
    return deskRect;
}

int QUIHelper::deskWidth()
{
    return getScreenRect().width();
}

int QUIHelper::deskHeight()
{
    return getScreenRect().height();
}

QSize QUIHelper::deskSize()
{
    return getScreenRect().size();
}

QWidget *QUIHelper::centerBaseForm=0;
void QUIHelper::setFormInCenter(QWidget *form)
{
    int formWidth=form->width();
    int formHeight=form->height();

    //如果=0标识采用系统桌面屏幕作为参照
    QRect rect;
    if(centerBaseForm==0)
    {
        rect=getScreenRect();
    }
    else
    {
        rect=centerBaseForm->geometry();
    }

    int deskWidth=rect.width();
    int deskHeight=rect.height();
    QPoint movePoint(deskWidth/2-formWidth/2+rect.x(),deskHeight/2-formHeight/2+rect.y());
    form->move(movePoint);
}

void QUIHelper::showForm(QWidget *form)
{
    setFormInCenter(form);
    form->show();

    if(form->width()+28>deskWidth()||form->height()+50>deskHeight())
        QMetaObject::invokeMethod(form, "showMaximized", Qt::QueuedConnection);
}

QString QUIHelper::appName()
{
    static QString name;
    if(name.isEmpty())
    {
        name=qApp->applicationFilePath();
        QStringList list=name.split("/");
        name=list.at(list.size()-1).split(".").at(0);
        name.replace("_armeabi-v7a", "");
        name.replace("_arm64-v8a", "");
    }

    return name;
}

QString QUIHelper::appPath()
{
    static QString path;
    if(path.isEmpty())
    {
        path=qApp->applicationDirPath();
    }
}

QStringList QUIHelper::getLocalIPs()
{
    static QStringList ips;
    if(ips.size()==0)
    {
        QList<QNetworkInterface> netInterfaces=QNetworkInterface::allInterfaces();
        foreach (QNetworkInterface netInterface, netInterfaces) {
            //移除虚拟机和抓包工具的虚拟网卡
            QString humanReadableName = netInterface.humanReadableName().toLower();
            if (humanReadableName.startsWith("vmware network adapter") || humanReadableName.startsWith("npcap loopback adapter")) {
                continue;
            }

            //过滤当前网络接口
            bool flag = (netInterface.flags() == (QNetworkInterface::IsUp | QNetworkInterface::IsRunning | QNetworkInterface::CanBroadcast | QNetworkInterface::CanMulticast));
            if (!flag) {
                continue;
            }

            QList<QNetworkAddressEntry> addrs=netInterface.addressEntries();
            foreach (QNetworkAddressEntry addr, addrs) {
                if(addr.ip().protocol()!=QAbstractSocket::IPv4Protocol){
                    continue;
                }

                QString ip4=addr.ip().toString();
                if(ip4!="127.0.0.1")
                {
                    ips<<ip4;
                }
            }
        }
    }

    return ips;
}

QList<QColor> QUIHelper::colors=QList<QColor>();
QList<QColor> QUIHelper::getColorList()
{
    //备用颜色集合 可以自行添加
    if (colors.size() == 0) {
        colors << QColor(0, 176, 180) << QColor(0, 113, 193) << QColor(255, 192, 0);
        colors << QColor(72, 103, 149) << QColor(185, 87, 86) << QColor(0, 177, 125);
        colors << QColor(214, 77, 84) << QColor(71, 164, 233) << QColor(34, 163, 169);
        colors << QColor(59, 123, 156) << QColor(162, 121, 197) << QColor(72, 202, 245);
        colors << QColor(0, 150, 121) << QColor(111, 9, 176) << QColor(250, 170, 20);
    }

    return colors;
}

QStringList QUIHelper::getColorNames()
{
    QList<QColor> colors=getColorList();
    QStringList colorNames;
    foreach (QColor color, colors) {
        colorNames<<color.name();
    }

    return colorNames;
}


QColor QUIHelper::getRandColor()
{
    QList<QColor> colors = getColorList();
    int index = getRandValue(0, colors.size(), true);
    return colors.at(index);
}

void QUIHelper::initRand()
{
    QTime t=QTime::currentTime();
    srand(t.msec()+t.second()*1000);
}

float QUIHelper::getRandFloat(float min, float max)
{
    double diff=fabs(max-min);
    double value=(double)(rand()%100)*100;
    value=min+value*diff;
    return value;
}

double QUIHelper::getRandValue(int min, int max, bool contansMin, bool contansMax)
{
    int value;
    if (contansMin) {
        if (contansMax) {
            value = min + 0 + (rand() % (max - min + 1));
        } else {
            value = min + 0 + (rand() % (max - min + 0));
        }
    } else {
        if (contansMax) {
            value = min + 1 + (rand() % (max - min + 0));
        } else {
            value = min + 1 + (rand() % (max - min - 1));
        }
    }

    return value;
}

QStringList QUIHelper::getRandPoint(int count, float mainLng, float mainLat, float dotLng, float dotLat)
{
    //随机生成坐标点
    QStringList points;
    for(int i=0;i<count;i++)
    {
        float lngx=getRandFloat(dotLng/10,dotLng);
        float latx=getRandFloat(dotLat/10,dotLat);

        //需要先用经度转换成字符串
        QString lng2=QString::number(mainLng+lngx,'f',8);
        QString lat2=QString::number(mainLat+latx,'f',8);
        QString point=QString("%1,%2").arg(lng2).arg(lat2);
        points<<point;
    }

    return points;
}

int QUIHelper::getRandValue(int oldMin, int oldMax, int oldValue, int newMin, int newMax)
{
    return (((oldValue-oldMin)*(newMax-newMin))/(oldMax-oldMin))+newMin;
}

QString QUIHelper::getUuid()
{
    QString uuid=QUuid::createUuid().toString();
    uuid.replace("{","");
    uuid.replace("}","");
    return uuid;
}

void QUIHelper::checkPath(const QString &dirName)
{
    //相对路径需要不全完整路径
    QString path=dirName;
    if(path.startsWith("./"))
    {
        path.replace(".","");
        path=QUIHelper::appPath()+path;
    }
    else if(!path.startsWith("/")&&!path.contains(":/"))
    {
        path=QUIHelper::appPath()+"/"+path;
    }

    //目录不存在则创建
    QDir dir(path);
    if(!dir.exists())
    {
        dir.mkpath(path);
    }
}

void QUIHelper::sleep(int msec)
{
    if(msec<0)
        return;

    QThread::sleep(msec);
}

void QUIHelper::setStyle()
{
    qApp->setStyle(QStyleFactory::create("Fusion"));

    //设置指定颜色
    QPalette palette;
    palette.setBrush(QPalette::Window,QColor("#F0F0F0"));
    qApp->setPalette(palette);
}

QFont QUIHelper::addFont(const QString &fontFile, const QString &fontName)
{
    //判断图形字体是否存在,不存在则加入
    QFontDatabase fontDb;
    if (!fontDb.families().contains(fontName)) {
        int fontId = fontDb.addApplicationFont(fontFile);
        QStringList listName = fontDb.applicationFontFamilies(fontId);
        if (listName.size() == 0) {
            qDebug() << QString("load %1 error").arg(fontName);
        }
    }

    //再次判断是否包含字体名称防止加载失败
    QFont font;
    if (fontDb.families().contains(fontName)) {
        font = QFont(fontName);
#if (QT_VERSION >= QT_VERSION_CHECK(4,8,0))
        font.setHintingPreference(QFont::PreferNoHinting);
#endif
    }

    return font;
}

void QUIHelper::setFont(int fontSize)
{
    QFont font;
    font.setFamily("MicroSoft Yahei");
    font.setPixelSize(fontSize);
    qApp->setFont(font);
}

void QUIHelper::setCode(bool utf8)
{
    if(utf8)
    {
        QTextCodec *code=QTextCodec::codecForName("utf-8");
        QTextCodec::setCodecForLocale(code);
    }
}

void QUIHelper::setTranslator(const QString &qmfile)
{
    //过滤下不存在的就不用设置
    if(!QFile(qmfile).exists())
    {
        return;
    }

    QTranslator *translator=new QTranslator(qApp);
    if(translator->load(qmfile))
    {
        qApp->installTranslator(translator);
    }
}

bool QUIHelper::checkPermission(const QString &permission)
{
    return true;
}

void QUIHelper::initAll(bool utf8, bool style, int fontSize)
{
    //初始化随机数种子
    QUIHelper::initRand();
    //设置编码
    QUIHelper::setCode(utf8);
    //设置字体
    QUIHelper::setFont(fontSize);
    //设置样式风格
    if(style)
    {
        QUIHelper::setStyle();
    }

    //设置翻译文件支持多个
    QUIHelper::setTranslator(":/qm/widgets.qm");
    QUIHelper::setTranslator(":/qm/qt_zh_CN.qm");
    QUIHelper::setTranslator(":/qm/designer_zh_CN.qm");

    //设置不使用本地系统环境代理配置
    QNetworkProxyFactory::setUseSystemConfiguration(false);
}

void QUIHelper::initMain(bool desktopSettingAware, bool useOpenGLES)
{
    //设置是否应用操作系统设置，比如字体
    QApplication::setDesktopSettingsAware(desktopSettingAware);

    //开启高分比率支持
    QApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    //不应用任何缩放
    QApplication::setAttribute(Qt::AA_Use96Dpi);
    if(useOpenGLES)
    {
        QApplication::setAttribute(Qt::AA_UseOpenGLES);
    }
}

QVector<int> QUIHelper::msgTypes = QVector<int>() << 0 << 1 << 2 << 3 << 4;
QVector<QString> QUIHelper::msgKeys = QVector<QString>() << QString::fromUtf8("发送") << QString::fromUtf8("接收") << QString::fromUtf8("解析") << QString::fromUtf8("错误") << QString::fromUtf8("提示");
QVector<QColor> QUIHelper::msgColors = QVector<QColor>() << QColor("#3BA372") << QColor("#EE6668") << QColor("#9861B4") << QColor("#FA8359") << QColor("#22A3A9");
QString QUIHelper::appendMsg(QTextEdit *textEdit, int type, const QString &data, int maxCount, int &currentCount, bool clear, bool pause)
{
    if(clear)
    {
        textEdit->clear();
        currentCount=0;
        return  QString();
    }

    if(pause)
    {
        return QString();
    }

    if(currentCount>=maxCount)
    {
        textEdit->clear();
        currentCount=0;
    }

    //不同类型不同颜色显示
    QString strType;
    int index=msgTypes.indexOf(type);
    if(index>=0)
    {
        strType=msgKeys.at(index);
        textEdit->setTextColor(msgColors.at(index));
    }

    //过滤回车换行符
    QString strData=data;
    strData.replace("\r","");
    strData.replace("\n","");
    strData=QString("时间[%1] %2 %3").arg(TIMES).arg(strType).arg(data);
    textEdit->append(strData);
    currentCount++;
    return strData;
}

void QUIHelper::setFramelessForm(QWidget *widgetMain, bool tool, bool top, bool menu)
{
    widgetMain->setProperty("form",true);
    widgetMain->setProperty("canMove",true);

    widgetMain->setWindowFlags(Qt::FramelessWindowHint);
    if(tool)
    {
        widgetMain->setWindowFlags(widgetMain->windowFlags()|Qt::Tool);
    }
    if(top)
    {
        widgetMain->setWindowFlags(widgetMain->windowFlags()|Qt::WindowStaysOnTopHint);
    }
    if(menu)
    {
        widgetMain->setWindowFlags(widgetMain->windowFlags()|Qt::WindowSystemMenuHint|Qt::WindowMinMaxButtonsHint);
    }
}

int QUIHelper::showMessageBox(const QString &text, int type, int closeSec, bool exec)
{
    int result=0;
    if(type==0)
    {
        showMessageBoxInfo(text,type,closeSec,exec);
    }
    else if(type==1)
    {
        showMessageBoxError(text,closeSec,exec);
    }
    else
    {
        result=showMessageBoxQuestion(text);
    }
    return result;
}

int QUIHelper::showMessageBoxInfo(const QString &text, int type, int closeSec, bool exec)
{
    QMessageBox box(QMessageBox::Information,"提示",text);
    box.setStandardButtons(QMessageBox::Yes);
    box.setButtonText(QMessageBox::Yes,QString("确定"));
    return box.exec();
}

int QUIHelper::showMessageBoxError(const QString &text, int closeSec, bool exec)
{
    QMessageBox box(QMessageBox::Critical,"错误",text);
    box.setStandardButtons(QMessageBox::Yes);
    box.setButtonText(QMessageBox::Yes,QString("确定"));
    return box.exec();
}

int QUIHelper::showMessageBoxQuestion(const QString &text)
{
    QMessageBox box(QMessageBox::Question, "询问", text);
    box.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
    box.setButtonText(QMessageBox::Yes, QString("确 定"));
    box.setButtonText(QMessageBox::No, QString("取 消"));
    return box.exec();
    //return QMessageBox::question(0, "询问", info, QMessageBox::Yes | QMessageBox::No);
}

void QUIHelper::initDialog(QFileDialog *dialog, const QString &title, const QString &acceptName,
                           const QString &dirName, bool native, int width, int height)
{
    //设置标题
    dialog->setWindowTitle(title);
    //设置标签文本
    dialog->setLabelText(QFileDialog::Accept, acceptName);
    dialog->setLabelText(QFileDialog::Reject, "取消(&C)");
    dialog->setLabelText(QFileDialog::LookIn, "查看");
    dialog->setLabelText(QFileDialog::FileName, "名称");
    dialog->setLabelText(QFileDialog::FileType, "类型");

    //设置默认显示目录
    if (!dirName.isEmpty()) {
        dialog->setDirectory(dirName);
    }

    //设置对话框宽高
    if (width > 0 && height > 0) {
#ifdef Q_OS_ANDROID
        bool horizontal = (QUIHelper::deskWidth() > QUIHelper::deskHeight());
        if (horizontal) {
            width = QUIHelper::deskWidth() / 2;
            height = QUIHelper::deskHeight() - 50;
        } else {
            width = QUIHelper::deskWidth() - 10;
            height = QUIHelper::deskHeight() / 2;
        }
#endif
        dialog->setFixedSize(width, height);
    }

    //设置是否采用本地对话框
    dialog->setOption(QFileDialog::DontUseNativeDialog, !native);
    //设置只读可以取消右上角的新建按钮
    //dialog->setReadOnly(true);
}

QString QUIHelper::getDialogResult(QFileDialog *dialog)
{
    QString result;
    if(dialog->exec()==QFileDialog::Accepted)
    {
        result=dialog->selectedFiles().first();
    }
    return result;
}

QString QUIHelper::getOpenFileName(const QString &filter, const QString &dirName,
                                   const QString &fileName, bool navtive, int width, int height)
{
    QFileDialog dialog;
    initDialog(&dialog,"保存文件","保存(&S)",dirName,navtive,width,height);

    //设置文件类型
    if(!filter.isEmpty())
    {
        dialog.setNameFilter(filter);
    }
    //设置默认文件名
    dialog.selectFile(fileName);

    //设置模态类型允许输入
    dialog.setWindowModality(Qt::WindowModal);
    //设置指定显示
    dialog.setWindowFlags(dialog.windowFlags()|Qt::WindowStaysOnTopHint);
    return getDialogResult(&dialog);
}

QString QUIHelper::getExistingDirectory(const QString &dirName, bool native, int width, int height)
{
    QFileDialog dialog;
    initDialog(&dialog, "选择目录", "选择(&S)", dirName, native, width, height);
    dialog.setReadOnly(true);
    //设置只显示目录
    dialog.setOption(QFileDialog::ShowDirsOnly);
    return getDialogResult(&dialog);
}

QString QUIHelper::getXorEncryptDecry(const QString &value, char key)
{
    //矫正范围外的数据
    if(key<0||key>=127)
    {
        key=127;
    }

    //大概从5.9版本，输出的加密字符串前面会加上 @String字符
    QString result=value;
    if(result.startsWith("@String"))
    {
        result=result.mid(8,result.length()-9);
    }

    int size=result.size();
    for(int i=0;i<size;i++)
    {
        result[i]=QChar(result.at(i).toLatin1()^key);
    }

    return result;
}

quint8 QUIHelper::getOrCode(const QByteArray &data)
{
    int len=data.length();
    quint8 result=0;
    for(int i=0;i<len;i++)
    {
        result ^=data.at(i);
    }

    return result;
}

quint8 QUIHelper::getCheckCode(const QByteArray &data)
{
    int len=data.length();
    quint8 result=0;
    for(int i=0;i<len;i++)
    {
        result +=data.at(i);
    }

    return result%256;
}

void QUIHelper::initTableView(QTableView *tableView, int rowHeight, bool headVisible, bool edit, bool stetchLasta)
{
    //设置弱属性用于应用qss特殊样式
    tableView->setProperty("model",true);
    //取消自动换行
    tableView->setWordWrap(false);
    //超出文本不显示省略号
    tableView->setTextElideMode(Qt::ElideNone);
    //奇数偶数行颜色交集
    tableView->setAlternatingRowColors(false);
    //垂直表头是否可见
    tableView->verticalHeader()->setVisible(headVisible);
    //选中一行表头是否加粗
    tableView->horizontalHeader()->setHighlightSections(false);
    //最后一行拉伸填充
    tableView->horizontalHeader()->setStretchLastSection(stetchLasta);
    //行标题最小宽度尺寸
    tableView->horizontalHeader()->setMinimumSectionSize(0);
    //行标题最小高度,等同于和默认行高一致
    tableView->horizontalHeader()->setFixedHeight(rowHeight);
    //默认行高
    tableView->verticalHeader()->setDefaultSectionSize(rowHeight);
    //选中时一行整体选中
    tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
    //只允许选择单个
    tableView->setSelectionMode(QAbstractItemView::SingleSelection);

    //表头不可单击
#if (QT_VERSION >= QT_VERSION_CHECK(5,0,0))
    tableView->horizontalHeader()->setSectionsClickable(false);
#else
    tableView->horizontalHeader()->setClickable(false);
#endif

    //鼠标按下即进入编辑模式
    if (edit) {
        tableView->setEditTriggers(QAbstractItemView::CurrentChanged | QAbstractItemView::DoubleClicked);
    } else {
        tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    }
}

void QUIHelper::openFile(const QString &fileName, const QString &msg)
{
    //文件不存在，则不用处理
    if(!QFile(fileName).exists())
    {
        return;
    }
    if(QUIHelper::showMessageBoxQuestion(msg+"成功，确定现在就打开吗？")==QMessageBox::Yes)
    {
        QString url=QString("file:///%1").arg(fileName);
        QDesktopServices::openUrl(QUrl(url,QUrl::TolerantMode));
    }
}

bool QUIHelper::checkIniFile(const QString &iniFile)
{
    //如果配置文件大小为零，则以初始值继续运行，并生成配置文件
    QFile file(iniFile);
    if(file.size()==0)
    {
        return false;
    }

    //如果配置文件不完整，则以初始值基线运行，并生成配置文件
    if(file.open(QFile::ReadOnly))
    {
        bool ok=true;
        while(!file.atEnd())
        {
            QString line=file.readLine();
            line.replace("\r","");
            line.replace("\n","");
            QStringList list=line.split("=");

            if(list.size()==2)
            {
                QString key=list.at(0);
                QString value=list.at(1);
                if(value.isEmpty())
                {
                    ok=false;
                    break;
                }
            }
        }

        if(!ok)
        {
            return false;
        }
    }
    else
    {
        return false;
    }

    return true;
}


QString QUIHelper::cutString(const QString &text, int len, int left, int right, bool file, const QString &mid)
{
    //如果指定了字符串分割则表示是文件名需要去掉拓展名
    QString result = text;
    if (file && result.contains(".")) {
        int index = result.lastIndexOf(".");
        result = result.mid(0, index);
    }

    //最终字符串格式为 前缀字符...后缀字符
    if (result.length() > len) {
        result = QString("%1%2%3").arg(result.left(left)).arg(mid).arg(result.right(right));
    }

    return result;
}

QRect QUIHelper::getCenteRect(const QSize &imageSize, const QRect &widgetRect, int borderWidth, int scaleMode)
{
    QSize newSize=imageSize;
    QSize widgetSize=widgetRect.size()-QSize(borderWidth*1,borderWidth*1);
    if(scaleMode==0)
    {
        if(newSize.width()>widgetSize.width()||newSize.height()>widgetSize.height())
        {
            newSize.scale(widgetSize,Qt::KeepAspectRatio);
        }
    }else if(scaleMode==1)
    {
        newSize.scale(widgetSize,Qt::KeepAspectRatio);
    }
    else
    {
        newSize=widgetSize;
    }

    int x = widgetRect.center().x() - newSize.width() / 2;
    int y = widgetRect.center().y() - newSize.height() / 2;
    //不是2的倍数需要偏移1像素
    x += (x % 2 == 0 ? 1 : 0);
    y += (y % 2 == 0 ? 1 : 0);
    return QRect(x, y, newSize.width(), newSize.height());
}

void QUIHelper::getScaledImage(QImage &image, const QSize &widgetSize, int scaleMode, bool fast)
{
    Qt::TransformationMode mode = fast ? Qt::FastTransformation : Qt::SmoothTransformation;
    if (scaleMode == 0) {
        if (image.width() > widgetSize.width() || image.height() > widgetSize.height()) {
            image = image.scaled(widgetSize, Qt::KeepAspectRatio, mode);
        }
    } else if (scaleMode == 1) {
        image = image.scaled(widgetSize, Qt::KeepAspectRatio, mode);
    } else {
        image = image.scaled(widgetSize, Qt::IgnoreAspectRatio, mode);
    }
}

QString QUIHelper::getTimeString(qint64 time)
{
    time=time/1000;
    QString min=QString("%1").arg(time/60,2,10,QChar('0'));
    QString sec=QString("%2").arg(time%60,2,10,QChar('0'));

    return QString("%1:%2").arg(min).arg(sec);
}

QString QUIHelper::getTimeString(QElapsedTimer timer)
{
    return QString::number(timer.elapsed()/1000,'f',3);
}

QString QUIHelper::getSizeString(quint64 size)
{
    float num=size;
    QStringList list;
    list<<"KB"<<"MB"<<"GB"<<"TB";

    QString uint("bytes");
    QStringListIterator i(list);
    while(num>1024.0&& i.hasNext())
    {
       uint =i.next();
       num /=1024.0;
    }

    return QString("%1 %2").arg(QString::number(num,'f',2)).arg(uint);
}
